package com.example.issue.ui.login

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.issue.R
import com.example.issue.network.Api
import com.example.issue.network.ApiClient
import com.example.issue.ui.issues.IssuesActivity
import kotlinx.coroutines.launch

class LoginActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        val email = findViewById<EditText>(R.id.email)
        val password = findViewById<EditText>(R.id.password)
        val btn = findViewById<Button>(R.id.loginBtn)

        btn.setOnClickListener {
            lifecycleScope.launch {
                try {
                    val token: Api.Token = ApiClient.api.login(Api.LoginIn(email.text.toString(), password.text.toString()))
                    ApiClient.setToken(token.access_token)
                    startActivity(Intent(this@LoginActivity, IssuesActivity::class.java))
                    finish()
                } catch (e: Exception) {
                    Toast.makeText(this@LoginActivity, "登录失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}
